package _4Game;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.*;

public class GameClientFrame extends JFrame implements KeyListener{

	
	JTextArea area;
	
	final static int N = 30;
	
	GameClient client;
	
	List<JPanel> panels = new ArrayList<>();
	
	public void showSnakes(List<Snake> snakes)
	{
		// 全部白色
		for(JPanel p:panels)
		{
			p.setBackground(Color.white);
		}
		
		for(Snake s:snakes)
		{
			for(Point p:s.body)
			{
				
				int index = p.x+p.y*N;
				if(index>=0&&index<panels.size())
				{
					JPanel tmp = panels.get(index);
					tmp.setBackground(Color.blue);
				}
			}
		}
	}

	public GameClientFrame() {
 
		
		// 多行文本框
//		area = new JTextArea();
//		// 滑动条区域
//		JScrollPane scroll = new JScrollPane(area);
//		area.setText("客户端准备");
//		this.add(scroll, BorderLayout.NORTH);
		
		// 繪製界面 
		JPanel p = new JPanel();
		p.setBackground(Color.CYAN);
		p.addKeyListener(this);
		p.setFocusable(true);
		
		p.setLayout(new GridLayout(N,N,3,3));
		for(int i=0;i<N;i++)
		{
			for(int j=0;j<N;j++)
			{
				JPanel tmp = new JPanel();
				tmp.setBackground(Color.white);
				p.add(tmp);
				
				panels.add(tmp);
			}
		}
		
		this.add(p);
		
		client = new GameClient();
		client.f = this;
		client.connect();

	}

	public static void main(String[] args) {

		GameClientFrame f = new GameClientFrame();

		f.setVisible(true);

		f.setBounds(100, 100, 600, 600);
		
		// 当关闭窗口 ，退出
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

	}

	@Override
	public void keyPressed(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyReleased(KeyEvent e) {
		
		System.out.println(e.getKeyCode());
		
		// 上38下40左37右39
		switch(e.getKeyCode())
		{
			case 38:
				client.send(0);
				break;
			case 40:
				client.send(1);
				break;
			case 37:
				client.send(2);
				break;
			case 39:
				client.send(3);
				break;
		}

		
		
	}

	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}
}
